const Service = require('egg').Service;

class MessageService extends Service {
  // 发送消息
  async sendMessage(messageData) {
    const { ctx } = this;
    const { sender_id, receiver_id, content, message_type, image_url, file_url } = messageData;
    
    // 验证发送者和接收者是否存在
    const [sender, receiver] = await Promise.all([
      ctx.model.User.findByPk(sender_id),
      ctx.model.User.findByPk(receiver_id)
    ]);
    
    if (!sender) {
      throw new Error('发送者不存在');
    }
    
    if (!receiver) {
      throw new Error('接收者不存在');
    }
    
    // 创建会话（如果不存在）
    const conversationService = this.ctx.service.conversation;
    const conversation = await conversationService.createOrGetConversation(sender_id, receiver_id);
    
    // 创建消息
    const message = await ctx.model.Message.create({
      sender_id,
      receiver_id,
      message_type: message_type || 'text',
      content: content || '',
      image_url: image_url || null,
      file_url: file_url || null,
      is_read: 0,
      created_at: new Date()
    });
    
    // 更新会话的最后一条消息
    await conversationService.updateLastMessage(conversation.id, message.id);
    
    return message;
  }
  
  // 获取会话的消息列表
  async getConversationMessages(conversationId, userId, query) {
    const { ctx } = this;
    const { page = 1, pageSize = 20 } = query;
    
    // 验证会话是否存在且当前用户是会话成员
    const conversation = await ctx.model.Conversation.findOne({
      where: {
        id: conversationId,
        [ctx.app.Sequelize.Op.or]: [
          { user1_id: userId },
          { user2_id: userId }
        ],
        is_active: 1
      }
    });
    
    if (!conversation) {
      throw new Error('会话不存在或已关闭');
    }
    
    // 获取消息列表
    const options = {
      where: {
        [ctx.app.Sequelize.Op.or]: [
          { 
            sender_id: conversation.user1_id,
            receiver_id: conversation.user2_id
          },
          { 
            sender_id: conversation.user2_id,
            receiver_id: conversation.user1_id
          }
        ]
      },
      limit: parseInt(pageSize),
      offset: (parseInt(page) - 1) * parseInt(pageSize),
      order: [['created_at', 'DESC']]
    };
    
    const { count, rows } = await ctx.model.Message.findAndCountAll(options);
    
    // 标记未读消息为已读
    await ctx.model.Message.update(
      { is_read: 1 },
      { 
        where: {
          receiver_id: userId,
          is_read: 0,
          [ctx.app.Sequelize.Op.or]: [
            { 
              sender_id: conversation.user1_id,
              receiver_id: conversation.user2_id
            },
            { 
              sender_id: conversation.user2_id,
              receiver_id: conversation.user1_id
            }
          ]
        }
      }
    );
    
    // 重置会话未读计数
    await this.ctx.service.conversation.resetUnreadCount(conversationId, userId);
    
    return {
      list: rows.reverse(), // 按时间正序返回
      pagination: {
        page: parseInt(page),
        pageSize: parseInt(pageSize),
        total: count,
        totalPages: Math.ceil(count / pageSize)
      }
    };
  }
  
  // 标记消息为已读
  async markAsRead(messageIds, userId) {
    const { ctx } = this;
    
    if (!messageIds || messageIds.length === 0) {
      throw new Error('消息ID不能为空');
    }
    
    const result = await ctx.model.Message.update(
      { is_read: 1 },
      { 
        where: {
          id: messageIds,
          receiver_id: userId,
          is_read: 0
        }
      }
    );
    
    return { updated: result[0] };
  }
  
  // 删除消息（仅删除自己的消息或自己收到的消息）
  async deleteMessage(messageId, userId) {
    const { ctx } = this;
    
    const message = await ctx.model.Message.findByPk(messageId);
    if (!message) {
      throw new Error('消息不存在');
    }
    
    // 只能删除自己发送的或收到的消息
    if (message.sender_id !== userId && message.receiver_id !== userId) {
      throw new Error('无权删除此消息');
    }
    
    await message.destroy();
    return true;
  }
  
  // 获取未读消息总数
  async getUnreadCount(userId) {
    const { ctx } = this;
    
    // 获取所有会话的未读消息总数
    const conversations = await ctx.model.Conversation.findAll({
      where: {
        [ctx.app.Sequelize.Op.or]: [
          { user1_id: userId },
          { user2_id: userId }
        ],
        is_active: 1
      },
      attributes: ['unread_count']
    });
    
    return conversations.reduce((total, conv) => total + (conv.unread_count || 0), 0);
  }
}

module.exports = MessageService;